#include "StdAfx.h"
#include "VersionUtils.h"


CVersionUtils::CVersionUtils(void)
{
}


CVersionUtils::~CVersionUtils(void)
{
}

CString CVersionUtils::GetAppName()
{
	return CVersionUtils::GetVersionInfo(L"ProductName"); 
}

CString CVersionUtils::GetAppVersion() 
{
	return CVersionUtils::GetVersionInfo(L"ProductVersion"); 
} 


CString CVersionUtils::GetVersionInfo(WCHAR* keyName) 
{
 WCHAR* AppName = L"VideoRecorder.exe";
 CString   AppVersion; 

 DWORD   RessourceVersionInfoSize; 
 DWORD   JustAJunkVariabel; 
 WCHAR*   VersionInfoPtr; 
 struct   LANGANDCODEPAGE
 { 
  WORD   wLanguage; 
  WORD   wCodePage; 
 }   *TranslationPtr; 
 WCHAR*     InformationPtr; 
 UINT      VersionInfoSize; 
 WCHAR     VersionValue[255]; 

 RessourceVersionInfoSize=GetFileVersionInfoSize(AppName,&JustAJunkVariabel); 
 if(0!=RessourceVersionInfoSize) 
 {
  VersionInfoPtr = new WCHAR[RessourceVersionInfoSize];
  if(!GetFileVersionInfo(AppName,0,RessourceVersionInfoSize,VersionInfoPtr)) 
  {
    ErrorExit((LPTSTR)L"GetFileVersionInfo");
   delete[]   VersionInfoPtr; 
   return NULL; 
  } 

  if(!VerQueryValue( VersionInfoPtr, L"VarFileInfo\\Translation", (LPVOID*)&TranslationPtr, &VersionInfoSize)) 
  { 
   ErrorExit((LPTSTR)L"VerQueryValue");
   delete[]   VersionInfoPtr; 
   return NULL; 
  } 

  // retrieve product version
  wsprintf(VersionValue, L"\\StringFileInfo\\%04x%04x\\%s", TranslationPtr[0].wLanguage, TranslationPtr[0].wCodePage,keyName); 

  if(!VerQueryValue( VersionInfoPtr, VersionValue, (LPVOID*)&InformationPtr, &VersionInfoSize)) 
  { 
   ErrorExit((LPTSTR)L"VerQueryValue");
   delete[]   VersionInfoPtr; 
   return NULL; 
  } 
  if(wcslen(InformationPtr)> 0)   //Not   Null 
  { 
   AppVersion=CString(InformationPtr); 
  } 

  delete[]   VersionInfoPtr; 
 } 
 return   AppVersion; 
} 

void CVersionUtils::ErrorExit(LPTSTR lpszFunction) 
{ 
 // Retrieve the system error message for the last-error code

 LPVOID lpMsgBuf;
 
 DWORD dw = GetLastError(); 

 FormatMessage(
  FORMAT_MESSAGE_ALLOCATE_BUFFER | 
  FORMAT_MESSAGE_FROM_SYSTEM |
  FORMAT_MESSAGE_IGNORE_INSERTS,
  NULL,
  dw,
  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  (LPTSTR) &lpMsgBuf,
  0, NULL );

 // Display the error message and exit the process
/*
 lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
  (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
*/
 CString displayInfo;
 displayInfo.Format(L"%s failed with error %d: %s",lpszFunction, dw, lpMsgBuf);
 MessageBox(NULL,displayInfo, TEXT("Error"), MB_OK); 

 LocalFree(lpMsgBuf);
}